$(document).ready(function() {
    // 新增行
    $('#addRow').click(function() {
        const newRow = `
            <tr class="calculation-row">
                <td>
                    <select name="product_sku" class="form-control sku-select" required>
                        <option value="">选择SKU</option>
                    </select>
                </td>
                <td>
                    <input type="number" name="required_quantity" 
                           class="form-control" min="1" value="1" required>
                </td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm remove-row">
                        <i class="bi bi-trash"></i> 删除
                    </button>
                </td>
            </tr>
        `;
        const $newRow = $(newRow);
        $('#calculationItems').append($newRow);
        const $select = $newRow.find('.sku-select');
        skuChoices.forEach(sku => {
            $select.append($('<option>', {
                value: sku,
                text: sku
            }));
        });
    });

    // 删除行
    $(document).on('click', '.remove-row', function() {
        if ($('.calculation-row').length > 1) {
            $(this).closest('.calculation-row').remove();
        } else {
            alert('至少保留一行记录');
        }
    });

    // 提交表单
    $('#stockCalculationForm').submit(function(e) {
        e.preventDefault();

        const formData = [];
        let isValid = true;

        $('.calculation-row').each(function() {
            const sku = $(this).find('[name="product_sku"]').val();
            const quantity = $(this).find('[name="required_quantity"]').val();

            if (!sku || !quantity) {
                isValid = false;
                return false;
            }

            formData.push({
                product_sku: sku,
                required_quantity: parseInt(quantity)
            });
        });

        if (!isValid) {
            alert('请填写所有必填字段');
            return;
        }

        $.ajax({
            url: '',
            type: 'POST',
            data: {
                form_data: JSON.stringify(formData),
                csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val()
            },
            success: function(response) {
                if (response.success) {
                    displayResults(response.products, response.materials);
                } else {
                    alert('计算失败: ' + (response.error || '未知错误'));
                }
            },
            error: function() {
                alert('服务器错误，请稍后重试');
            }
        });
    });

    // 显示计算结果
    function displayResults(products, materials) {
        const $productTable = $('#productSummary tbody');
        const $materialTable = $('#materialSummary tbody');

        $productTable.empty();
        $materialTable.empty();

        // 填充产品数据
        products.forEach(product => {
            $productTable.append(`
                <tr>
                    <td>${product.product_sku}</td>
                    <td>${product.required_quantity}</td>
                    <td>${product.current_stock}</td>
                    <td class="${product.production_needed > 0 ? 'text-danger fw-bold' : 'text-success'}">
                        ${product.production_needed}
                    </td>
                </tr>
            `);
        });

        // 填充物料数据
        for (const [sku, data] of Object.entries(materials)) {
            $materialTable.append(`
                <tr>
                    <td>${sku}</td>
                    <td>${data.required}</td>
                    <td>${data.current}</td>
                    <td class="${data.shortage > 0 ? 'text-danger fw-bold' : 'text-success'}">
                        ${data.shortage}
                    </td>
                </tr>
            `);
        }

        $('#calculationResult').show();
    }
});